﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

namespace WebApi.Hubs;

/// <summary>
/// Authorization requirement to restrict access based on domain.
/// </summary>
public class DomainRestrictedRequirement : AuthorizationHandler<DomainRestrictedRequirement, HubInvocationContext>, IAuthorizationRequirement
{
    /// <summary>
    /// Handles the authorization requirement for SignalR hub invocations based on the user's domain.
    /// </summary>
    /// <param name="context"></param>
    /// <param name="requirement"></param>
    /// <param name="resource"></param>
    /// <returns></returns>
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DomainRestrictedRequirement requirement, HubInvocationContext resource)
    {
        if (context.User.Identity != null 
            && !string.IsNullOrEmpty(context.User.Identity.Name) 
            && IsAllowedTodoThis(resource.HubMethodName, context.User.Identity.Name) 
            && context.User.Identity.Name.EndsWith("@microsoft.com"))
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }

    private bool IsAllowedTodoThis(string hubMethodName, string currentUserName)
    {
        return (currentUserName.Equals("wja@microsoft.com") && hubMethodName.Equals("banUser", StringComparison.OrdinalIgnoreCase));
    }
}
